package com.ashbur.rookie.files.controller;

import com.ashbur.rookie.api.controller.files.FileUploaderControllerApi;
import com.ashbur.rookie.common.exception.GraceException;
import com.ashbur.rookie.common.grace.result.GraceJSONResult;
import com.ashbur.rookie.common.grace.result.ResponseStatusEnum;
import com.ashbur.rookie.common.utils.FileUtils;
import com.ashbur.rookie.common.utils.extend.AliImageReviewUtils;
import com.ashbur.rookie.files.resource.FileResource;
import com.ashbur.rookie.files.service.UploaderService;
import com.ashbur.rookie.pojo.bo.NewAdminBO;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSFindIterable;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.client.model.Filters;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
public class FileUploaderController implements FileUploaderControllerApi {
    final static Logger logger = LoggerFactory.getLogger(FileUploaderController.class);

    @Autowired
    private UploaderService uploaderService;

    @Autowired
    private FileResource fileResource;

    @Autowired
    private AliImageReviewUtils aliImageReviewUtils;

    @Autowired
    private GridFSBucket gridFSBucket;


    @Override
    public GraceJSONResult uploadFace(String userId,
                                      MultipartFile file) throws Exception {

        logger.info("this is file host {}",fileResource.getOssHost());

        String path = "";
        if (file != null) {
            // 获得文件上传的名称
            String fileName = file.getOriginalFilename();

            // 判断文件名不能为空
            if (StringUtils.isNotBlank(fileName)) {
                String fileNameArr[] = fileName.split("\\.");
                // 获得后缀
                String suffix = fileNameArr[fileNameArr.length - 1];
                // 判断后缀符合我们的预定义规范
                if (!suffix.equalsIgnoreCase("png") &&
                        !suffix.equalsIgnoreCase("jpg") &&
                        !suffix.equalsIgnoreCase("jpeg")
                ) {
                    return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_FORMATTER_FAILD);
                }

                // 执行上传
                path = uploaderService.uploadOSS(file, userId, suffix);

            } else {
                return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
            }
        } else {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        }

        logger.info("path = " + path);

        String finalPath = "";
        if (StringUtils.isNotBlank(path)) {
            finalPath = fileResource.getOssHost() + path;
//            finalPath = fileResource.getOssHost() + path;
        } else {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }

        // return GraceJSONResult.ok(doAliImageReview(finalPath));
        return GraceJSONResult.ok(finalPath);
    }

    @Override
    public GraceJSONResult uploadSomeFiles(String userId,
                                           MultipartFile[] files)
            throws Exception {


        // 声明list，用于存放多个图片的地址路径，返回到前端
        List<String> imageUrlList = new ArrayList<>();
        if (files != null && files.length > 0) {
            for (MultipartFile file : files) {
                String path = "";
                if (file != null) {
                    // 获得文件上传的名称
                    String fileName = file.getOriginalFilename();

                    // 判断文件名不能为空
                    if (StringUtils.isNotBlank(fileName)) {
                        String fileNameArr[] = fileName.split("\\.");
                        // 获得后缀
                        String suffix = fileNameArr[fileNameArr.length - 1];
                        // 判断后缀符合我们的预定义规范
                        if (!suffix.equalsIgnoreCase("png") &&
                                !suffix.equalsIgnoreCase("jpg") &&
                                !suffix.equalsIgnoreCase("jpeg")
                        ) {
                            continue;
                        }

                        // 执行上传
//                        path = uploaderService.uploadFdfs(file, suffix);
                        path = uploaderService.uploadOSS(file, userId, suffix);

                    } else {
                        continue;
                    }
                } else {
                    continue;
                }

                String finalPath = "";
                if (StringUtils.isNotBlank(path)) {
//                    finalPath = fileResource.getHost() + path;
                    finalPath = fileResource.getOssHost() + path;
                    // FIXME: 放入到imagelist之前，需要对图片做一次审核
                    imageUrlList.add(finalPath);
                } else {
                    continue;
                }
            }
        }

        return GraceJSONResult.ok(imageUrlList);
    }


    @Override
    public GraceJSONResult uploadToGridFS(NewAdminBO newAdminBO,
                                          HttpServletRequest request,
                                          HttpServletResponse response) throws Exception {

        // base64字符串
        String file64 = newAdminBO.getImg64();
        // 将字符串转换为byte数组
        byte[] bytes = new BASE64Decoder().decodeBuffer(file64.trim());
        // 转化为输入流
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        // 上传
        ObjectId fileId = gridFSBucket.uploadFromStream(newAdminBO.getUsername() + ".png", inputStream);
        logger.info("上传完成。 文件ID：{}" , fileId);

        // 文件在mongodb中的id
        String fileIDStr = fileId.toString();

        logger.info("fileIDStr={}" , fileIDStr);

        return GraceJSONResult.ok(fileIDStr);
    }

    @Override
    public void readInGridFS(String faceId,
                             HttpServletRequest request,
                             HttpServletResponse response) throws Exception {

        if (StringUtils.isBlank(faceId) || faceId.equalsIgnoreCase("null")) {
            GraceException.display(ResponseStatusEnum.FILE_NOT_EXIST_ERROR);
        }

        // 获取内容
        File file = readGridFSByFaceId(faceId);

        FileUtils.downloadFileByStream(response, file);
    }


    /**
     * 从GridFS中读取文件内容
     * @param faceId
     * @return
     */
    private File readGridFSByFaceId(String faceId) throws Exception {
        // 获取内容
        GridFSFindIterable gridFSFindIterable = null;
        try {
            gridFSFindIterable = gridFSBucket.find(Filters.eq("_id", new ObjectId(faceId)));
        } catch (IllegalArgumentException e) {
            GraceException.display(ResponseStatusEnum.FILE_NOT_EXIST_ERROR);
        }
        GridFSFile gridFSFile = gridFSFindIterable.first();

        if (gridFSFile == null) {
            GraceException.display(ResponseStatusEnum.FILE_NOT_EXIST_ERROR);
        }
        logger.info("filename: {} " + gridFSFile.getFilename());
        String fileName = gridFSFile.getFilename();
        // 获取文件流，定义存放位置和名称
        String TEMP_PATH = "/Users/eumenides/Desktop/菜鸟客栈/workspaces/temp_face";
        File fileTemp = new File(TEMP_PATH);
        if (!fileTemp.exists()) {
            fileTemp.mkdirs();
        }
        File file = new File(TEMP_PATH + "/" + fileName);
        // 创建输出流
        OutputStream os = new FileOutputStream(file);
        // 执行下载，下载到本地磁盘，管理员头像不多，下载到服务器不会占用大量硬盘空间
        gridFSBucket.downloadToStream(new ObjectId(faceId), os);
        return file;
    }

    @Override
    public GraceJSONResult readFace64InGridFS(String faceId,
                                              HttpServletRequest request,
                                              HttpServletResponse response) throws Exception {
        // 1. 判断faceId不能为空
        if (StringUtils.isBlank(faceId)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_NOT_EXIST_ERROR);
        }

        // 2. 获得文件
        File file = readGridFSByFaceId(faceId);

        // 3. 把文件转换为base64并返回给调用方
        String base64 = FileUtils.fileToBase64(file);

        return GraceJSONResult.ok(base64);
    }





    public static final String FAILED_IMAGE_URL = "https://imooc-news.oss-cn-shanghai.aliyuncs.com/image/faild.jpeg";
    private String doAliImageReview(String pendingImageUrl) {

        /**
         * fastdfs 默认存在于内网，无法被阿里云内容管理服务检查到
         * 需要配置到公网才行：
         * 1. 内网穿透，natppp/花生壳/ngrok
         * 2. 路由配置端口映射
         * 3. fdfs 发布到云服务器
         */
        boolean result = false;
        try {
            result = aliImageReviewUtils.reviewImage(pendingImageUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (!result) {
            return FAILED_IMAGE_URL;
        }

        return pendingImageUrl;
    }
}
